package com.nervenets.general.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Objects;

/**
 * Created by Joe
 * Date: 2011-4-30 23:51:24
 */
public final class HttpTools {
    private static final Log log = LogFactory.getLog(HttpTools.class);
    private static final CloseableHttpClient httpClient = HttpClients.createDefault();

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-real-ip");//先从nginx自定义配置获取
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static long getIp(HttpServletRequest request) {
        final String ipAddress = HttpTools.getIpAddress(request);
        return NumberUtil.ipToLong(ipAddress);
    }

    public static HttpServletRequest getHttpRequest() {
        try {
            return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    public static String getHttpRequestUri() {
        try {
            return Objects.requireNonNull(getHttpRequest()).getRequestURI();
        } catch (Exception e) {
            return null;
        }
    }

    public static Object getHttpRequestAttribute(String key) {
        try {
            return Objects.requireNonNull(getHttpRequest()).getAttribute(key);
        } catch (Exception e) {
            return null;
        }
    }

    public static String getRequestInfo(HttpServletRequest request) {
        StringBuilder content = new StringBuilder();
        content.append("URL ：").append(request.getRequestURL()).append("<br>");
        content.append("<br>IP ：").append(HttpTools.getIpAddress(request));
        content.append("<br>Headers ：<br>");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);
            content.append(key).append(":").append(value).append("<br>");
        }
        content.append("<br>Params ：<br>");
        for (Object key : request.getParameterMap().keySet()) {
            content.append(key).append(":").append(request.getParameter(String.valueOf(key))).append("<br>");
        }
        content.append("<br>Body ：<br>");
        content.append(getRequestBody(request)).append("<br><br>");

        return content.toString();
    }

    public static String getRequestBody(HttpServletRequest request) {
        if (request.getContentLength() > 0) {
            byte[] body = new byte[request.getContentLength()];
            try {
                IOUtils.readFully(request.getInputStream(), body);
            } catch (IOException e) {
                return "请求内容读取错误：" + e.getMessage();
            }
            final String result = new String(body);
            if (JSON.isValid(result)) {
                return JSON.toJSONString(JSON.parse(result), true);
            }
            return result;
        } else
            return "";
    }

    public static String post(String url, String body) {
        return HttpUtil.post(url, body);
    }

    public static String post(String url, Map<String, Object> form) {
        return HttpUtil.post(url, form);
    }

    public static String get(String url) {
        return HttpUtil.get(url);
    }
}
